<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="3.5">
        <div>
          <el-radio-group v-model="radio" size="medium" @change="handleChange">
            <el-radio-button v-for="(option, index) in radioOption" :key="index" :label="option.value"
              :disabled="option.disabled">
              {{ option.label }}
            </el-radio-button>
          </el-radio-group>
        </div>
      </el-col>
      <el-col :span="3.5">
        <el-cascader v-model="siteValues" :options="options" :props="props" collapse-tags clearable placeholder="全部站点"
          @change="handleChange"></el-cascader>
      </el-col>
      <el-col :span="3.5">
        <el-cascader v-model="authValues" :options="platFormOptions" :props="authProps" collapse-tags clearable
          placeholder="全部店铺" @change="handleChange"></el-cascader>
      </el-col>
      <el-col :span="3.5">
        <el-date-picker v-model="dateValue" type="daterange" align="right" unlink-panels range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="handleChange">
        </el-date-picker>
      </el-col>
      <el-col :span="2">
        <el-select v-model="value" filterable placeholder="请选择币种">
          <el-option v-for="item in currencyOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <!-- 导出按钮 -->
      <el-col :span="2">
        <el-button type="primary" icon="el-icon-download" :loading="exportLoading" @click="exportExcel"  v-hasPermi="['walmart:orderInstant:list']">
          导出
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="salesList" style="width: 100%" ref="salesTable">
      <el-table-column type="selection" align="center" fixed />
      <el-table-column label="图片" width="100" fixed>
        <template slot-scope="scope">
          <image-preview v-if="scope.row.imgName" :src="scope.row.imgName" :width="50" :height="50" />
          <i v-else class="no-image-icon"><image-preview :src="scope.row.productName" :width="50" :height="50" /></i>
        </template></el-table-column>
      <el-table-column label="商品名称" width="400" prop="name"></el-table-column>
      <el-table-column label="SKU" width="150" prop="sku"></el-table-column>
      <el-table-column label="链接名称" width="400" prop="productName">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="链接名称" width="600" trigger="hover" :content="scope.row.productName">
            <span slot="reference">{{ scope.row.productName.slice(0, 39)
              }}<span v-if="scope.row.productName.length > 39">...</span></span>
          </el-popover>
          <br />
        </template>
      </el-table-column>
      <el-table-column label="sellerSKU" width="150" prop="sellerSku"></el-table-column>
      <el-table-column label="店铺/站点" width="150">
        <template slot-scope="scope">
          {{ scope.row.shopName }}&nbsp;&nbsp;/&nbsp;&nbsp;{{ scope.row.site }}
        </template>
      </el-table-column>

      <el-table-column label="今日销量/今日销售额" width="150" v-if="todayColumn">
        <template slot-scope="scope">
          <span>{{ scope.row.qty }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.totalAmount
            }}</span>
        </template>
      </el-table-column>

      <el-table-column label="昨日销量/昨日销售额" width="150" v-if="yesterdayColumn">
        <template slot-scope="scope">
          <span>{{ scope.row.qty }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.totalAmount
            }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="currentOption" width="180" v-if="shouldHideColumn">
        <template slot-scope="scope">
          <span>{{ scope.row.qty }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.totalAmount
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="近3天销量/售额" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.qty3days > 0">{{ scope.row.qty3days }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.total3days
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="近7天销量/售额" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.qty7days > 0">{{ scope.row.qty7days }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.total7days
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="近15天销量/售额" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.qty15days > 0">{{ scope.row.qty15days }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.total15days
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="近30天销量/售额" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.qty30days > 0">{{ scope.row.qty30days }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.total30days
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="近60天销量/售额" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.qty60days > 0">{{ scope.row.qty60days }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.total60days
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="近90天销量/售额" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.qty90days > 0">{{ scope.row.qty90days }}&nbsp;&nbsp;/&nbsp;&nbsp;${{
            scope.row.total90days
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="可售库存" width="150" prop="sellableInventory">
      </el-table-column>
      <el-table-column label="不可售库存" width="150" prop="unsellableInventory"></el-table-column>
      <el-table-column label="预计可售天数" width="150" prop="estimateAvailableDays">
        <template slot="header">
          <span>预计可售天数</span>&nbsp;&nbsp;
          <el-tooltip content="可售库存除近30天日均销量" effect="dark" placement="top">
            <svg-icon icon-class="question"></svg-icon>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="工厂待交货数量" width="150" prop="factoryQuantityNumber">
        <template slot="header">
          <span>工厂待交货数量</span>&nbsp;&nbsp;
          <el-tooltip content="采购订单工厂为出货的数量" effect="dark" placement="top">
            <svg-icon icon-class="question"></svg-icon>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="近30天日均销量" width="150" prop="thirtySales"></el-table-column>
      <el-table-column label="GTIN" width="150" prop="gtin"></el-table-column>
      <el-table-column label="品牌" width="150" prop="brand"></el-table-column>
    </el-table>

    <div style="margin-top: -11px; height: 50px">
      <pagination v-show="total > 0" :total="total" :page.sync="instantSales.pageNum"
        :limit.sync="instantSales.pageSize" @pagination="getBase()" />
    </div>
  </div>
</template>

<script>
import { getPlatFormTree, getSiteFormTree } from "@/api/walmart/auth";
import { getInstant } from "@/api/walmart/sale";
import { getSelectMonetaryTreeList } from "@/api/procured/plan";
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      salesList: [],
      loading: false,
      exportLoading: false, // 导出 loading 状态
      radio: "销量",
      radioOption: [
        // 存储选项的数组
        { label: "销量", value: "销量", disabled: false },
        { label: "订单量", value: "订单量", disabled: false },
        { label: "销售额", value: "销售额", disabled: false },
      ],
      value: "",
      props: { multiple: true },
      authProps: { multiple: true },
      options: [],
      siteValues: [],
      authValues: [],
      platFormOptions: [],
      currencyOptions: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              end.setTime(end.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      dateValue: [new Date(), new Date()],
      currentOption: "", // 当前选项
      shouldHideColumn: false,
      todayColumn: false,
      yesterdayColumn: false,
      instantSales: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dayDifference: 0,
    };
  },
  created() {
    this.getPlatForm();
    this.getSiteForm();
    this.getMonetary();
    this.getBase();
  },
  methods: {
    /** 查询店铺名称列表 */
    getPlatForm() {
      getPlatFormTree().then((response) => {
        this.platFormOptions = response.data;
      });
    },
    /** 查询站点列表 */
    getSiteForm() {
      getSiteFormTree().then((response) => {
        this.options = response.data;
      });
    },
    /** 货币单位 */
    getMonetary() {
      getSelectMonetaryTreeList().then((response) => {
        this.currencyOptions = response.data;
      });
    },
    getBase() {
      if (this.radio == "销量") {
        // 使用 flatMap() 遍历并拆分外部数组，去除 null 值
        let filteredData = this.siteValues.flatMap((innerArray) => {
          // 使用 filter() 过滤掉内部数组中的 null 值
          return innerArray.filter((value) => value !== null);
        });
        this.instantSales.sites = filteredData;

        // 使用 flatMap() 遍历并拆分外部数组，去除 null 值
        let authData = this.authValues.flatMap((innerArray) => {
          // 使用 filter() 过滤掉内部数组中的 null 值
          return innerArray.filter((value) => value !== null);
        });
        this.instantSales.authIds = authData;

        for (let i = 0; i < this.dateValue.length; i++) {
          // 获取当前日期
          const currentDate = new Date(this.dateValue[i]);
          // 提取年、月、日
          const year = currentDate.getFullYear();
          const month = String(currentDate.getMonth() + 1).padStart(2, "0"); // 月份从0开始，补齐成两位数
          const day = String(currentDate.getDate()).padStart(2, "0"); // 补齐成两位数

          // 判断i的值，根据i的值赋值给startTime或者endTime
          if (i === 0) {
            this.instantSales.startTime = `${year}-${month}-${day}`;
            const difference = Math.abs(
              currentDate.getTime() - new Date().getTime()
            );
            // 将毫秒数转换为天数
            this.dayDifference = Math.ceil(difference / (1000 * 3600 * 24));
            if (this.dayDifference == 1 || this.dayDifference == 0) {
              this.todayColumn = true;
              this.yesterdayColumn = false;
              this.shouldHideColumn = false;
            } else if (this.dayDifference == 2) {
              this.yesterdayColumn = true;
              this.todayColumn = false;
              this.shouldHideColumn = false;
            } else if (this.dayDifference == 8) {
              this.todayColumn = false;
              this.yesterdayColumn = false;
              this.shouldHideColumn = true;
              this.currentOption = "近7天销量/售额";
            } else if (this.dayDifference == 31) {
              this.todayColumn = false;
              this.yesterdayColumn = false;
              this.shouldHideColumn = true;
              this.currentOption = "近30天销量/售额";
            } else if (this.dayDifference == 91) {
              this.todayColumn = false;
              this.yesterdayColumn = false;
              this.shouldHideColumn = true;
              this.currentOption = "近90天销量/售额";
            }
          } else if (i === 1) {
            this.instantSales.endTime = `${year}-${month}-${day}`;
          }
        }

        getInstant(this.instantSales).then((response) => {
          this.salesList = response.rows;
          console.info(response.rows);
          this.total = response.total;
        });
      } else {
        this.salesList = null;
        this.total = 0;
      }
    },
    handleChange() {
      this.getBase();
    },
    /** 导出Excel（支持选中导出） */
    async exportExcel() {
      this.exportLoading = true;

      try {
        // 获取选中的行数据，如果没有选中则导出全部
        const selectedRows = this.$refs.salesTable ? this.$refs.salesTable.selection : [];
        let dataToExport;

        if (selectedRows.length > 0) {
          // 如果有选中行，只导出选中行
          dataToExport = selectedRows;
        } else {
          // 没有选中行，重新查询所有数据（不分页）
          const exportParams = {
            ...this.instantSales,
            pageNum: 1,
            pageSize: 999999 // 设置一个很大的数字，或者你的后端支持 -1 表示不分页
          };

          this.$message.info('正在获取所有数据，请稍候...');
          const response = await getInstant(exportParams);
          dataToExport = response.rows || [];

          if (dataToExport.length === 0) {
            this.$message.warning('没有数据可导出！');
            this.exportLoading = false;
            return;
          }
        }

        // 收集所有唯一的日期
        const allDates = new Set();
        dataToExport.forEach(row => {
          if (row.dailySalesList && row.dailySalesList.length > 0) {
            row.dailySalesList.forEach(dailySale => {
              if (dailySale.orderDate) {
                // 将日期格式化为YYYY-MM-DD
                const date = new Date(dailySale.orderDate);
                const formattedDate = date.toISOString().split('T')[0];
                allDates.add(formattedDate);
              }
            });
          }
        });

        // 将日期排序
        const sortedDates = Array.from(allDates).sort();

        // 计算dailySalesList的汇总数据
        const dailyTotals = {};
        sortedDates.forEach(date => {
          dailyTotals[date] = { qty: 0, amount: 0 };
        });

        // 计算所有商品的总销量和总销售额
        let grandTotalQty = 0;
        let grandTotalAmount = 0;

        dataToExport.forEach(row => {
          if (row.dailySalesList && row.dailySalesList.length > 0) {
            row.dailySalesList.forEach(dailySale => {
              if (dailySale.orderDate) {
                const date = new Date(dailySale.orderDate);
                const formattedDate = date.toISOString().split('T')[0];
                dailyTotals[formattedDate].qty += dailySale.dailyQty || 0;
                dailyTotals[formattedDate].amount += parseFloat(dailySale.dailyAmount || 0);

                // 累计总的销量和销售额
                grandTotalQty += dailySale.dailyQty || 0;
                grandTotalAmount += parseFloat(dailySale.dailyAmount || 0);
              }
            });
          }
        });

        // 准备导出的数据
        const exportData = [];

        // 添加汇总行
        const summaryRow = {
          '商品名称': '【每日汇总】',
          'SKU': '',
          '链接名称': '',
          'sellerSKU': '',
          'GTIN': '',
          '店铺/站点': '',
          '总销量': grandTotalQty,
          '总销售额': `$${grandTotalAmount.toFixed(2)}`
        };

        sortedDates.forEach(date => {
          summaryRow[`${date} 销量`] = dailyTotals[date].qty;
          summaryRow[`${date} 销售额`] = `$${dailyTotals[date].amount.toFixed(2)}`;
        });

        exportData.push(summaryRow);

        // 添加空行分隔
        const emptyRow = {
          '商品名称': '',
          'SKU': '',
          '链接名称': '',
          'sellerSKU': '',
          'GTIN': '',
          '店铺/站点': '',
          '总销量': '',
          '总销售额': ''
        };

        sortedDates.forEach(date => {
          emptyRow[`${date} 销量`] = '';
          emptyRow[`${date} 销售额`] = '';
        });

        exportData.push(emptyRow);

        // 添加详细数据
        dataToExport.forEach(row => {
          const data = {
            '商品名称': row.name || '',
            'SKU': row.sku || '',
            '链接名称': row.productName || '',
            'sellerSKU': row.sellerSku || '',
            'GTIN': row.gtin || '',
            '店铺/站点': `${row.shopName || ''}/${row.site || ''}`
          };

          // 计算当前SKU的总销量和总销售额
          let totalQty = 0;
          let totalAmount = 0;

          // 将每日销售数据转换为Map以便快速查找
          const dailySalesMap = {};
          if (row.dailySalesList && row.dailySalesList.length > 0) {
            row.dailySalesList.forEach(dailySale => {
              if (dailySale.orderDate) {
                const date = new Date(dailySale.orderDate);
                const formattedDate = date.toISOString().split('T')[0];
                dailySalesMap[formattedDate] = dailySale;

                // 累计总销量和总销售额
                totalQty += dailySale.dailyQty || 0;
                totalAmount += parseFloat(dailySale.dailyAmount || 0);
              }
            });
          }

          // 添加总销量和总销售额列
          data['总销量'] = totalQty;
          data['总销售额'] = `$${totalAmount.toFixed(2)}`;

          // 添加每日销售数据
          sortedDates.forEach(date => {
            const dailySale = dailySalesMap[date];
            if (dailySale) {
              data[`${date} 销量`] = dailySale.dailyQty || 0;
              data[`${date} 销售额`] = `$${dailySale.dailyAmount || 0}`;
            } else {
              data[`${date} 销量`] = 0;
              data[`${date} 销售额`] = '$0';
            }
          });

          // 只导出有数据的天数列（值大于0的）
          if (row.qty3days > 0) {
            data['近3天销量'] = row.qty3days;
            data['近3天销售额'] = `$${row.total3days || 0}`;
          }
          if (row.qty7days > 0) {
            data['近7天销量'] = row.qty7days;
            data['近7天销售额'] = `$${row.total7days || 0}`;
          }
          if (row.qty15days > 0) {
            data['近15天销量'] = row.qty15days;
            data['近15天销售额'] = `$${row.total15days || 0}`;
          }
          if (row.qty30days > 0) {
            data['近30天销量'] = row.qty30days;
            data['近30天销售额'] = `$${row.total30days || 0}`;
          }
          if (row.qty60days > 0) {
            data['近60天销量'] = row.qty60days;
            data['近60天销售额'] = `$${row.total60days || 0}`;
          }
          if (row.qty90days > 0) {
            data['近90天销量'] = row.qty90days;
            data['近90天销售额'] = `$${row.total90days || 0}`;
          }

          exportData.push(data);
        });

        // 创建工作簿
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet(exportData);

        // 设置列宽（动态调整）
        const colWidths = [
          { wch: 30 }, // 商品名称
          { wch: 20 }, // SKU
          { wch: 40 }, // 链接名称
          { wch: 20 }, // sellerSKU
          { wch: 15 }, // GTIN
          { wch: 25 }, // 店铺/站点
          { wch: 15 }, // 总销量
          { wch: 18 }  // 总销售额
        ];

        // 为销量/销售额列添加列宽
        const additionalCols = Array(sortedDates.length * 2 + 12).fill({ wch: 15 });
        ws['!cols'] = [...colWidths, ...additionalCols];

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '销售数据');

        // 生成文件名
        const now = new Date();
        const timeStr = now.getFullYear() +
          String(now.getMonth() + 1).padStart(2, '0') +
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') +
          String(now.getMinutes()).padStart(2, '0');

        const filename = `销售数据_${timeStr}.xlsx`;

        // 导出文件
        XLSX.writeFile(wb, filename);

        const exportCount = dataToExport.length;
        const message = selectedRows.length > 0
          ? `成功导出${exportCount}条选中数据！`
          : `成功导出${exportCount}条数据！`;
        this.$message.success(message);

      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试！');
      } finally {
        this.exportLoading = false;
      }
    }

  },
};
</script>

<style>
.el-radio-button__orig-radio:checked+.el-radio-button__inner {
  color: #1890ff;
  background-color: #fff;
  border-color: #1890ff;
  -webkit-box-shadow: -1px 0 0 0 #1890ff;
  box-shadow: -1px 0 0 0 #1890ff;
}
</style>
